package com.robusta.app.web.controller;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.robusta.app.catalogue.api.CatalogueOperations;
import com.robusta.app.domain.catalogue.CatalogueEntry;
import com.robusta.app.web.model.GridViewModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.transform;
import static com.robusta.app.web.model.GridViewModel.RowViewModel;

@Controller
@RequestMapping("catalogue")
public class CatalogueController {
    private CatalogueOperations catalogueOperations;
    @Autowired
    public CatalogueController(CatalogueOperations catalogueOperations) {
        this.catalogueOperations = catalogueOperations;
    }

    @RequestMapping(value = "search", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    public @ResponseBody
    GridViewModel searchCatalogue(@ModelAttribute GridViewModel.SearchData searchData, @ModelAttribute GridViewModel.PageData pageData, @ModelAttribute GridViewModel.SortData sortData) {
        int totalEntries = catalogueOperations.searchCountFor(searchData);
        // When there are no search items, skip call to get paged and sorted data.
        List<RowViewModel> rows = totalEntries == 0? Lists.<RowViewModel>newArrayList(): transform(catalogueOperations.searchEntries(searchData, pageData, sortData), toRowViewModel());
        return new GridViewModel(
                pageData,
                totalEntries,
                rows);
    }

    private Function<CatalogueEntry, RowViewModel> toRowViewModel() {
        return new Function<CatalogueEntry, RowViewModel>() {
            @Override
            public RowViewModel apply(CatalogueEntry input) {
                return new RowViewModel(input.id().intValue(), newArrayList(
                        String.valueOf(input.id()),
                        input.description(),
                        input.domain().toString(),
                        input.laterallyEnabled().toString(),
                        input.active().toString()));
            }
        };
    }

}
